package network;

import java.net.DatagramPacket;
import java.net.InetAddress;
import java.nio.ByteBuffer;

import shared.Vec2f;
import vmo.Actor;

public class Packet_State extends Packet
{
//all the state information from the server
	public ActorState [] m_states;
	public int m_count;
	public Packet_State(ActorState [] actorstate, int timestamp)
	{
		m_states=actorstate;
		m_timestamp=timestamp;
		m_type=packettype.STATE;
		m_count=actorstate.length;
		for (int i=0;i<actorstate.length;i++)
		{
			if (m_states[i]==null)
			{
				m_count=i;
				break;
			}
		}
	}
	
	public Packet_State(DatagramPacket pack)
	{
		m_address=pack.getAddress();
		m_type=packettype.STATE;		
		ByteBuffer buffer=ByteBuffer.wrap(pack.getData());
		Header(pack.getAddress(),buffer);	
		
		//read states
		int d=buffer.get();
		m_states=new ActorState[d];
		for (int i=0;i<d;i++)
		{
			m_states[i]=new ActorState();
			//read z
			m_states[i].m_z=buffer.get();
			//read position
			m_states[i].m_pos=new Vec2f(buffer.getFloat(),buffer.getFloat());
			
			m_states[i].m_uid=buffer.getShort();
			//read recording
			m_states[i].m_record=new byte[12];
			for (int j=0;j<12;j++)
			{
				m_states[i].m_record[j]=buffer.get();
			}
			
		}
		
	}
	
	public DatagramPacket Encode(InetAddress address, int port)
	{
		byte []buffer=new byte[1024];
		ByteBuffer BB=ByteBuffer.wrap(buffer);		
		//encode type
		BB.put(getTypebyte(m_type));
		BB.putInt(m_timestamp);		
		//write states;
		BB.put((byte)m_count);
		for (int i=0;i<m_count;i++)
		{
			//write each actor state into the buffer
			
			//write z
			BB.put(m_states[i].m_z);
			//write position
			BB.putFloat(m_states[i].m_pos.x);
			BB.putFloat(m_states[i].m_pos.y);
			
			BB.putShort(m_states[i].m_uid);
			//write recording
			for (int j=0;j<12;j++)
			{
				BB.put(m_states[i].m_record[j]);
			}
		}
		return new DatagramPacket(buffer,buffer.length,address,port);
	}		
}
